<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

/**
 * 系统邮件发送函数
 * @param string $to 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function send_mail($to, $name, $subject = '', $body = '', $attachment = null) {

    // Instantiation and passing `true` enables exceptions
    $mail = new PHPMailer(true);

    try {
        //Server settings
        $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->Encoding = "base64"; //编码方式
        $mail->SMTPDebug = 2; // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
        $mail->isSMTP(); // Set mailer to use SMTP
        /*$mail->Mailer = 'SMTP';*/
        $mail->SMTPAuth = true; // 启用 SMTP 验证功能
        $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
        $mail->Host = sysconf('email_host'); // Specify main and backup SMTP servers
        $mail->Port = sysconf('email_port'); // SMTP服务器的端口号
        $mail->Username = sysconf('email_username'); // SMTP username
        $mail->Password = sysconf('email_password'); // SMTP password
        $mail->title = sysconf('email_title'); // SMTP password

        //Recipients
        $mail->setFrom(sysconf('email_username'), sysconf('email_title'));
        $mail->AddAddress($to, $name); // Add a recipient
        // $mail->addCC('cc@example.com');
        // $mail->addBCC('bcc@example.com');
        // $replyEmail = ''; //留空则为发件人EMAIL
        // $replyName = ''; //回复名称（留空则为发件人名称）
        // $mail->AddReplyTo($replyEmail, $replyName);

        // Attachments
        if (is_array($attachment)) {
            // 添加附件
            foreach ($attachment as $file) {
                is_file($file) && $mail->AddAttachment($file);
            }
        }

        // Content
        $mail->isHTML(true); // Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        $mail->send();
        // echo 'Message has been sent';
        return true;
    } catch (Exception $e) {
        // echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        return $mail->ErrorInfo;
    }
}